package com.atguigu.gmall.index.service;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.index.annotation.GmallCache;
import com.atguigu.gmall.index.config.RedissonConfig;
import com.atguigu.gmall.index.feign.GmallPmsClient;
import com.atguigu.gmall.index.utils.DistributedLock;
import com.atguigu.gmall.pms.entity.CategoryEntity;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author fenge
 */
@Service
public class IndexService {
    @Autowired
    private GmallPmsClient pmsClient;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private DistributedLock distributedLock;

    @Autowired
    private RedissonClient redissonClient;

    private static final String KEY_PREFIX = "index:cates:";
    private static final String LOCK_PREFIX = "index:cates:lock:";

    public List<CategoryEntity> queryLvl1Categories() {
        ResponseVo<List<CategoryEntity>> listResponseVo = pmsClient.queryCategoriesByPid(0l);
        return listResponseVo.getData();
    }

    @GmallCache(prefix = KEY_PREFIX, timeout = 129600, random = 14400, lock = LOCK_PREFIX)
    public List<CategoryEntity> queryLvl12CategoriesByPid(Long pid) {
        ResponseVo<List<CategoryEntity>> listResponseVo = pmsClient.queryCategoriesWithSubsByPid(pid);
        List<CategoryEntity> categoryEntities = listResponseVo.getData();
        return categoryEntities;
    }

    /*@GmallCache(prefix = KEY_PREFIX, timeout = 90 * 24 * 60, random = 14400, lock = LOCK_PREFIX)
    public List<CategoryEntity> queryLvl12CategoriesByPid(Long pid) {
        // 1.先查询缓存,缓存命中直接返回
        String json = redisTemplate.opsForValue().get(KEY_PREFIX + pid);
        if (StringUtils.isNotBlank(json)) {
            return JSON.parseArray(json, CategoryEntity.class);
        }

        RLock fairLock = redissonClient.getFairLock(LOCK_PREFIX + pid);
        fairLock.lock();


        try {
            String json2 = redisTemplate.opsForValue().get(KEY_PREFIX + pid);
            if (StringUtils.isNotBlank(json2)) {
                return JSON.parseArray(json2, CategoryEntity.class);
            }
            // 2.如果缓存没有命中,则发送远程请求,查询数据库,并放入缓存

            ResponseVo<List<CategoryEntity>> listResponseVo = pmsClient.queryCategoriesWithSubsByPid(pid);
            List<CategoryEntity> categoryEntities = listResponseVo.getData();

            if (CollectionUtils.isEmpty(categoryEntities)) {
                redisTemplate.opsForValue().set(KEY_PREFIX + pid, JSON.toJSONString(categoryEntities), 5, TimeUnit.MINUTES);
            } else {
                redisTemplate.opsForValue().set(KEY_PREFIX + pid, JSON.toJSONString(categoryEntities), 90 * 24 + new Random().nextInt(20), TimeUnit.HOURS);
            }

            return categoryEntities;
        } finally {
            fairLock.unlock();
        }
    }*/

    public void testLock() {
        RLock lock = redissonClient.getLock("lock");
        lock.lock();
        try {
            String json = redisTemplate.opsForValue().get("num");
            if (StringUtils.isBlank(json)) {
                redisTemplate.opsForValue().set("num", "1");
            }
            int num = Integer.parseInt(json);
            redisTemplate.opsForValue().set("num", String.valueOf(++num));
        } finally {
            lock.unlock();
        }
    }

    /*public void testLock3() {
        String uuid = UUID.randomUUID().toString();
        Boolean lock = distributedLock.tryLock("lock", uuid, 30);
        if (lock){
            String json = redisTemplate.opsForValue().get("num");
            if (StringUtils.isBlank(json)) {
                redisTemplate.opsForValue().set("num", "1");
            }
            int num = Integer.parseInt(json);
            redisTemplate.opsForValue().set("num", String.valueOf(++num));
//            testSubLock(uuid);
            try {
                TimeUnit.SECONDS.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            distributedLock.unlock("lock",uuid);
        }

    }*/

    public void testSubLock(String uuid) {
        distributedLock.tryLock("lock", uuid, 30);

        System.out.println("测试可重入锁");

        distributedLock.unlock("lock", uuid);
    }

    public synchronized void testLock2() {
        String uuid = UUID.randomUUID().toString();
        Boolean flag = this.redisTemplate.opsForValue().setIfAbsent("lock", uuid, 10, TimeUnit.SECONDS);
        if (!flag) {
            try {
                Thread.sleep(80);
                testLock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
//            redisTemplate.expire("lock",10,TimeUnit.SECONDS);
            String json = redisTemplate.opsForValue().get("num");
            if (StringUtils.isBlank(json)) {
                redisTemplate.opsForValue().set("num", "1");
            }
            int num = Integer.parseInt(json);
            redisTemplate.opsForValue().set("num", String.valueOf(++num));

            String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
            redisTemplate.execute(new DefaultRedisScript<>(script, Boolean.class), Arrays.asList("lock"), uuid);

            /*if (StringUtils.equals(uuid,redisTemplate.opsForValue().get("lock"))){
                redisTemplate.delete("lock");
            }*/

        }


    }
}
